package com.ligq.h265toupinpush.avmetting

import android.content.Context
import android.util.Log
import com.ligq.common.utils.NetUtils
import org.java_websocket.WebSocket
import org.java_websocket.client.WebSocketClient
import org.java_websocket.handshake.ClientHandshake
import org.java_websocket.handshake.ServerHandshake
import org.java_websocket.server.WebSocketServer
import java.net.InetSocketAddress
import java.net.URI
import java.nio.ByteBuffer


const val PORT_MEETING = 9901

//需要有一个server端，n个client端
class SocketLive(iPeer: IPeerConnection) {
    private val clients = mutableListOf<MeetingSocketClient>()
    private val urls = arrayOf(
        "ws://192.168.1.3:",//小米5
        "ws://192.168.1.2:",//nova7
        "ws://192.168.1.6:"//小米mix2
    )
    private var meetingServer: MeetingSocketServer = MeetingSocketServer(iPeer)

    init {
        meetingServer.start()
    }

    fun start(context: Context) {
        for (url in urls) {
            if (url.contains(NetUtils.getLocalIpAddress(context)!!)) {
                continue
            }
            var isSame = false
            for (client in clients) {
                if (url.contains(client.uri)) {
                    isSame = true
                    break
                }
            }
            if (isSame) {
                continue
            }

            try {
                val uri = URI(url + PORT_MEETING)
                val meetingSocketClient = MeetingSocketClient(url, uri)
                meetingSocketClient.connect()
                if (meetingSocketClient.isOpen) {
                    clients.add(meetingSocketClient)
                }
            } catch (e: Exception) {
                Log.e(TAG, "start: ", e)
            }
        }
    }

    fun sendData(encodeData: ByteArray) {
        for (client in clients) {
            if (client.isOpen) {
                client.send(encodeData)
            }
        }
    }


    inner class MeetingSocketClient(val uri: String, serverUri: URI) : WebSocketClient(serverUri) {
        override fun onOpen(handshakedata: ServerHandshake?) {
            Log.d(TAG, "MeetingSocketClient onOpen: ")
            clients.add(this)

        }

        override fun onMessage(message: String?) {
            Log.d(TAG, "MeetingSocketClient onMessage: $message")
        }

        override fun onClose(code: Int, reason: String?, remote: Boolean) {
            Log.d(TAG, "MeetingSocketClient onClose: ")
            clients.remove(this)
        }

        override fun onError(ex: java.lang.Exception?) {
            Log.e(TAG, "MeetingSocketClient onError: ", ex)
            clients.remove(this)
        }

    }

    inner class MeetingSocketServer(private val iPeer: IPeerConnection) :
        WebSocketServer(InetSocketAddress(PORT_MEETING)) {
        override fun onOpen(conn: WebSocket?, handshake: ClientHandshake?) {
            Log.d(TAG, "onOpen: ")
            conn?.let {
                iPeer.newConnection(it.remoteSocketAddress.address.hostAddress)
            }

        }

        override fun onClose(conn: WebSocket?, code: Int, reason: String?, remote: Boolean) {
            Log.d(TAG, "onClose: ")
        }

        override fun onMessage(conn: WebSocket?, message: String?) {
            Log.d(TAG, "onMessage: $message")
        }

        override fun onError(conn: WebSocket?, ex: Exception?) {
            Log.e(TAG, "onError: ", ex)
        }

        override fun onStart() {
            Log.d(TAG, "onStart: ")
        }

        override fun onMessage(conn: WebSocket?, message: ByteBuffer?) {
            Log.d(TAG, "onMessage: $message")
            val data = ByteArray(message!!.remaining())
            message.get(data)
            iPeer.remoteReceiveData(conn!!.remoteSocketAddress.address.hostAddress, data)
        }

    }
}